//
//  XQBaseIdentityChoosePopView.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/10.
//

import UIKit

class XQBaseIdentityChoosePopView: UIView {

    var sureHandle: ((String) -> Void)?
    
    var cancelHandle: (() -> Void)?
    
    var selectRow : Int = 2
        
    private lazy var contentView : UIView = {
        let v = UIView()
        return v
    }()
    
    private lazy var bgImageView : UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "pop_base_bg")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    private lazy var sureBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("OK", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .mainTextColor
        btn.layer.cornerRadius = 24
        btn.addTarget(self, action: #selector(sureClick), for: .touchUpInside)
        return btn
    }()
    
    private lazy var calcelBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Close", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = 24
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.white.cgColor
        btn.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
        return btn
    }()
    
    private lazy var titleLb : UILabel = {
        let lb = UILabel()
        lb.text = "Please select"
        lb.textColor = .white
        lb.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        return lb
    }()
    
    private lazy var tableView : UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = true
        tableView.register(XQBaseIndentityChoosePopCell.self, forCellReuseIdentifier: "XQBaseIndentityChoosePopCell")
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    private lazy var middleView : UIView = {
        let view = UIView()
        view.backgroundColor = .mainTextColor
        return view
    }()
    
    var dataSource : [String] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    var selectData : String = "" {
        didSet {
            var index = 0
            for (idx,_) in dataSource.enumerated() {
                if dataSource[idx] == selectData {
                    index = idx
                    break
                }
            }
            
            self.selectRow = index + 2
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.scrollContentOffset(index: self.selectRow)
                self.tableView.reloadData()
            }

        }
    }    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isUserInteractionEnabled = true
        makeUI()
        makeConstraints()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
        makeConstraints()
    }
    
    private func makeUI() {
        self.addSubview(self.contentView)
        self.contentView.addSubview(self.bgImageView)
        self.contentView.addSubview(self.sureBtn)
        self.contentView.addSubview(self.calcelBtn)
        self.bgImageView.addSubview(self.titleLb)
        self.bgImageView.addSubview(self.middleView)
        self.bgImageView.addSubview(self.tableView)
    }
    
    private func makeConstraints() {
        self.contentView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        self.bgImageView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.width.equalTo(UIDevice.xq_width() - 32)
            make.height.equalTo(420)
        }
        self.sureBtn.snp.makeConstraints { make in
            make.top.equalTo(self.bgImageView.snp.bottom).offset(30)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(48)
        }
        self.calcelBtn.snp.makeConstraints { make in
            make.top.equalTo(self.sureBtn.snp.bottom).offset(15)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(48)
            make.bottom.equalTo(0)
        }
        self.titleLb.snp.makeConstraints { make in
            make.top.equalTo(65)
            make.left.equalTo(24)
            make.height.equalTo(16)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.titleLb.snp.bottom).offset(20)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(46 * 6)
        }
        self.middleView.snp.makeConstraints { make in
            make.top.equalTo(self.titleLb.snp.bottom).offset(20 + 46 * 2)
            make.left.right.equalTo(0)
            make.height.equalTo(46)
        }
    }
    
    @objc private func sureClick() {
        sureHandle?(dataSource[selectRow - 2])
    }
    
    @objc private func cancelClick() {
        cancelHandle?()
    }
}

extension XQBaseIdentityChoosePopView : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count + 5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQBaseIndentityChoosePopCell", for: indexPath) as! XQBaseIndentityChoosePopCell
        
        if (indexPath.row == 0 || 
            indexPath.row == 1 ||
            indexPath.row == dataSource.count + 4 ||
            indexPath.row == dataSource.count + 3 ||
            indexPath.row == dataSource.count + 2) {
            cell.content = ""
        }else {
            cell.content = "\(dataSource[indexPath.row - 2])"
        }
        
        let middleOne = indexPath.row == selectRow - 1 ||  indexPath.row == selectRow + 1
        let middleTwo = indexPath.row == selectRow - 2 || indexPath.row == selectRow - 3 ||  indexPath.row == selectRow + 2
        cell.position(middle: selectRow == indexPath.row, middleOne: middleOne, middleTwo: middleTwo)
        cell.onTapHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.tableViewDidSelectAtIndexPath(indexPath: indexPath)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 46
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        selectRow = -1
        self.tableView.reloadData()
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let rowH = 46.0
        let targetY = targetContentOffset.pointee.y
        
        var targetRow = Int(targetY / rowH + (velocity.y > 0 ? 0.5 : -0.5))
        targetRow = max(0, min(targetRow, dataSource.count - 1))

        selectRow = targetRow + 2
        targetContentOffset.pointee.y = CGFloat(targetRow) * rowH
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        handle()
    }
    
    private func tableViewDidSelectAtIndexPath(indexPath : IndexPath) {
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == dataSource.count + 4 || indexPath.row == dataSource.count + 3  || indexPath.row == dataSource.count + 2) {
            return
        }
        
        self.selectRow = indexPath.row
        
        scrollContentOffset(index: self.selectRow)
        handle()
    }
    
    private func scrollContentOffset(index : Int) {
        if (index < 2) {
            self.tableView.setContentOffset(.zero, animated: true)
        }else {
            self.tableView.setContentOffset(CGPoint(x: 0, y: 46.0 * Double(index - 2)), animated: true)
        }
    }
    
    private func handle() {
        self.tableView.reloadData()
    }

}
